import UIKit

class GridCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    private let cellIdentifier = "GridCell"
    private let itemsPerRow = 5
    private let itemCount = 100
    private var selectedItems = Set<IndexPath>() // 存储选中的单元格索引

    override func viewDidLoad() {
        super.viewDidLoad()
        setupCollectionView()
    }

    private func setupCollectionView() {
        collectionView.backgroundColor = .systemBackground
        collectionView.register(GridCell.self, forCellWithReuseIdentifier: cellIdentifier)
        
        if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            flowLayout.minimumLineSpacing = 10
            flowLayout.minimumInteritemSpacing = 10
            flowLayout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        }
    }

    // MARK: - UICollectionViewDataSource

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return itemCount
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! GridCell
        cell.configure(with: indexPath.item + 1, isSelected: selectedItems.contains(indexPath))
        return cell
    }

    // MARK: - UICollectionViewDelegateFlowLayout

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let padding: CGFloat = 10
        let availableWidth = view.bounds.width - (padding * CGFloat(itemsPerRow + 1))
        let itemWidth = availableWidth / CGFloat(itemsPerRow)
        return CGSize(width: itemWidth, height: itemWidth)
    }

    // MARK: - UICollectionViewDelegate

    // 处理单元格选中事件
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if selectedItems.contains(indexPath) {
            selectedItems.remove(indexPath) // 如果已选中，则取消选中
        } else {
            selectedItems.insert(indexPath) // 如果未选中，则添加到选中集合
        }
        
        // 刷新选中的单元格以更新外观
        collectionView.reloadItems(at: [indexPath])
    }
}

class GridCell: UICollectionViewCell {
    static let identifier = "GridCell"

    private let label: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.textColor = .white
        label.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupViews()
    }

    private func setupViews() {
        contentView.addSubview(label)

        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
            label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
        ])

        contentView.layer.cornerRadius = 8
        contentView.layer.masksToBounds = true
        
        // 设置默认边框属性
        layer.borderWidth = 0
        layer.borderColor = UIColor.blue.cgColor
        layer.cornerRadius = 8
        layer.masksToBounds = false
        layer.shadowOffset = CGSize(width: 0, height: 0)
        layer.shadowRadius = 2
        layer.shadowOpacity = 0.3
    }

    func configure(with number: Int, isSelected: Bool = false) {
        label.text = "\(number)"
        contentView.backgroundColor = randomColor()
        
        // 根据选中状态设置边框
        layer.borderWidth = isSelected ? 3 : 0
        layer.shadowOpacity = isSelected ? 0.3 : 0
    }

    private func randomColor() -> UIColor {
        let red = CGFloat.random(in: 0...1)
        let green = CGFloat.random(in: 0...1)
        let blue = CGFloat.random(in: 0...1)
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }
}    
